<?php
include('/home/content/o/k/h/okh1234/html/test/wp-blog-header.php');
global $wpdb;

// Search terms
$srch = urldecode($_POST['searchText']);
if($srch == '')
$srchtxt ='';
else
$srchtxt = "AND (a.name LIKE %s)";

$cat = str_replace(","," OR b.institution_type = ",urldecode($_POST['mycat']));
$dist = str_replace(","," OR b.district_id = ",urldecode($_POST['mydist']));

// Default search query
$qry = $wpdb->prepare("SELECT a.*, b.institution_type FROM om_points a, institution_table b WHERE ((a.institution_id = b.institution_id) AND (a.name LIKE '%s')) ORDER BY name ASC", "%$srch%");

// Length of search string
$len = strlen($srch);

//exit();

// Category and District not set (Search ALL)
if($cat == 0 && $dist == 0){
	// Do not entertain any search string less than 3 characters
	// Prevents overloading database
	// Normally prevented on client side, only triggers if client side inactive
	if($len < 3){
	echo "Invalid Search!";
	exit();
	}
}
// At least one of the fields is set
else{
	//echo "$cat!$dist";
	//exit();
	// Both fields set
	$qry = $wpdb->prepare("SELECT a.*, b.institution_type FROM om_points a, institution_table b WHERE ((a.institution_id = b.institution_id) ".$srchtxt." AND (b.institution_type = $cat) AND (b.district_id = $dist)) ORDER BY a.name ASC","%$srch%");
	// Only category set
	if($dist == 0)
	$qry = $wpdb->prepare("SELECT a.*, b.institution_type FROM om_points a, institution_table b WHERE ((a.institution_id = b.institution_id) $srchtxt AND (b.institution_type = $cat)) ORDER BY a.name ASC","%$srch%");
	// Only district set
	if($cat == 0)
	$qry = $wpdb->prepare("SELECT a.*, b.institution_type FROM om_points a, institution_table b WHERE ((a.institution_id = b.institution_id) $srchtxt AND (b.district_id = $dist)) ORDER BY a.name ASC","%$srch%");
}
// Run Query
$result = $wpdb->get_results($qry,ARRAY_A);

// Check Result
if($result) {
// Continue	

} 
// Something is not right.
else {
	if($num_rows < 1)
	die("No results!");
	else
	die ("Couldn't connect!");
}
/*
$tr = '<ul id="srchres">';
foreach($result as $r) {
	$r = str_replace("'","\'",$r);
	$tr .= "<li><a onclick='displayMap(" . json_encode($r) . ")' href='javascript:void(0)'>" . $r["name"] . "</a></li>";
}
$tr .= "</ul>";
*/
$tr = array();
foreach($result as $r) {
	$tr []= $r;
}
print json_encode($tr);
//echo json_encode($rows, JSON_FORCE_OBJECT);
?>